package com.dycx.api.config;

import com.dycx.common.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * @author Abel
 * @version 1.0
 * @Date 2021-03-15 17:13
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public RestResponse<?> exceptionHandler(Exception e) {
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        StringBuilder stringBuilder = new StringBuilder("[系统错误！" + e.getClass().getName() + ": " + e.getMessage() + "]\n");
        for (StackTraceElement stackTraceElement : stackTraceElements) {
            String s = stackTraceElement.toString();
            if (s.startsWith("com.jn")) {
                stringBuilder.append(s).append("\n");
            }
        }
        e.printStackTrace();

//        // 获取异常的调用栈信息
//        StackTraceElement[] stackTrace = e.getStackTrace();
//        // 打印异常的位置信息
//        for (StackTraceElement element : stackTrace) {
//            System.out.println(element.getClassName() + "." + element.getMethodName() + "(" + element.getFileName() + ":" + element.getLineNumber() + ")");
//        }

        return RestResponse.fail("exceptionHandler:"+e.getMessage());
    }

    /**
     * 参数校验
     *
     * @param e e
     * @return RestResponse
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class, ConstraintViolationException.class})
    @ResponseBody
    public RestResponse<?> handleValidException(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException me = (MethodArgumentNotValidException) e;
            return wrapperBindingResult(me.getBindingResult());
        }
        if (e instanceof BindException) {
            BindException be = (BindException) e;
            return wrapperBindingResult(be.getBindingResult());
        }
        if (e instanceof ConstraintViolationException) {
            return wrapperConstraintViolationExceptionResult((ConstraintViolationException) e);
        }
        log.error("全局异常==========================handleValidException:{}",e.getMessage());
        e.printStackTrace();
        return RestResponse.fail("handleValidException:"+"参数错误");
    }

    private RestResponse<?> wrapperConstraintViolationExceptionResult(ConstraintViolationException e) {
        StringBuilder msg = new StringBuilder();
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        if (CollectionUtils.isEmpty(constraintViolations)) {
            return RestResponse.fail("参数错误");
        }
        for (ConstraintViolation<?> item : constraintViolations) {
            String propertyPath = item.getPropertyPath().toString();
            msg.append(", ").append(propertyPath.split("\\.")[1]).append(": ").append(item.getMessage());
            break;
        }
        log.error("全局异常==========================wrapperConstraintViolationExceptionResult:{}",e.getMessage());
        e.printStackTrace();
        return RestResponse.fail("wrapperConstraintViolationExceptionResult:"+msg.substring(2));
    }

    private RestResponse<?> wrapperBindingResult(BindingResult bindingResult) {
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        if (CollectionUtils.isEmpty(allErrors)) {
            return RestResponse.fail("参数错误");
        }
        log.error("全局异常==========================wrapperBindingResult:{}",allErrors.get(0).getDefaultMessage());
        return RestResponse.fail("wrapperBindingResult:"+allErrors.get(0).getDefaultMessage());
    }
}
